package com.common.baselibrary.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.common.baselibrary.log.LogUtil;

import java.io.File;
import java.math.BigDecimal;
import java.util.List;


public class SystemUtils {

    private static final String TAG = "SystemUtils";

    public static final int DEFAULT_TASK_NUM = 100;

    public static List<RunningTaskInfo> getRunningTask(Context context) {
        return getRunningTask(context, DEFAULT_TASK_NUM);
    }

    public static List<RunningTaskInfo> getRunningTask(Context context, int num) {
        if (context != null) {
            ActivityManager am = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningTaskInfo> rTasks = am.getRunningTasks(1);
            return rTasks;
        }
        return null;
    }

    public static boolean isTopActivity(Activity activity) {
        return isTopActivity(activity, activity.getClass());
    }

    public static boolean isTopActivity(Context context,
                                        Class<? extends Activity> activity) {
        return isTopActivity(context, activity.getName());
    }

    /**
     * 判断当前的activity是否为top activity
     *
     * @param context
     * @param className
     * @return
     */
    public static boolean isTopActivity(Context context, String className) {
        List<RunningTaskInfo> rTasks = getRunningTask(context, 1);
        if (rTasks != null) {
            for (RunningTaskInfo task : rTasks) {
                Log.d("SystemUtils", "isTopActivity:" + task.topActivity.getClassName()
                        + "|" + className);
                if (task.topActivity.getClassName().equals(className)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断当前应用的是否为后台task
     *
     * @param context
     * @return
     */
    public static boolean isAppBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {//5.0及之后
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                //前台程序
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            String packName = context.getPackageName();
            List<RunningTaskInfo> rTasks = getRunningTask(context, 1);
            if (null != rTasks && rTasks.size() > 0) {
                RunningTaskInfo task = rTasks.get(0);
                if (packName.equalsIgnoreCase(task.topActivity.getPackageName())) {
                    isInBackground = false;
                }
            }
        }
        LogUtil.i(TAG, "isAppBackground: " + isInBackground);
        return isInBackground;
    }

    /**
     * 获取系统Meta属性值
     *
     * @param context
     * @param metaDataName
     * @return
     */
    public static String getMetaData(Context context, String metaDataName) {
        String metaData = "";
        try {
            ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            Object object = applicationInfo.metaData.get(metaDataName);
            if (object != null) {
                metaData = object.toString();
            }
        } catch (Exception var4) {
            LogUtil.w(TAG, "catch Exception throw by getChannelNo.");
        }
        return metaData;
    }

    /**
     * 获取APP的versionName
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            versionName = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionName;
        } catch (Exception e) {
            LogUtil.w(TAG, "catch Exception throw by getAppVersionName.");
        }
        return versionName;
    }

    /**
     * 获取APP的versionCode
     */
    public static int getAppVersionCode(Context context) {
        int versionCode = 0;
        try {
            versionCode = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (Exception e) {
            LogUtil.w(TAG, "catch Exception throw by getAppVersionCode.");
        }
        return versionCode;
    }

    /**
     * 获取手机的设备ID
     */
    public static String getDeviceId(Context context) {
        String deviceId = "";
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager != null) {
            deviceId = telephonyManager.getDeviceId();
        }
        if (TextUtils.isEmpty(deviceId)) {
            deviceId = "unknown";
        }
        return deviceId;
    }

    /**
     * 判断是否是主进程
     */
    public static boolean isCurrentAppProcess(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcessList = mActivityManager.getRunningAppProcesses();
        if (null != appProcessList && appProcessList.size() > 0) {
            for (ActivityManager.RunningAppProcessInfo appProcess : appProcessList) {
                if (appProcess.pid == pid && context.getPackageName().equals(appProcess.processName)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取App安装包信息
     *
     * @return package info
     */
    public static PackageInfo getPackageInfo(Context context) {
        PackageInfo info = null;
        if (context != null) {
            try {
                info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            } catch (PackageManager.NameNotFoundException e) {
                LogUtil.w(TAG, "catch NameNotFoundException throw by getPackageInfo.", e);
            }
        }
        if (info == null) {
            info = new PackageInfo();
        }
        return info;
    }


    /**
     * 判断是否是某个进程
     */
    public static boolean isAppProcess(Context context, String processName) {
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcessList = mActivityManager.getRunningAppProcesses();
        if (null != appProcessList && appProcessList.size() > 0) {
            for (ActivityManager.RunningAppProcessInfo appProcess : appProcessList) {
                if (appProcess.pid == pid && processName.equals(appProcess.processName)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取缓存大小
     * @param context
     * @return
     * @throws Exception
     */
    public static String getTotalCacheSize(Context context) throws Exception {
        long cacheSize = getFolderSize(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            cacheSize += getFolderSize(context.getExternalCacheDir());
        }
        return getFormatSize(cacheSize);
    }

    /**
     * 清除缓存
     * @param context
     */
    public static void clearAllCache(Context context) {
        deleteDir(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            deleteDir(context.getExternalCacheDir());
        }
    }
    private static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }

    // 获取文件大小
    //Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录，一般放一些长时间保存的数据
    //Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录，一般存放临时缓存数据
    public static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }
    /**
     * 格式化单位
     * @param size
     * @return
     */
    public static String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
//            return size + "Byte";
            return "0K";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
              .toPlainString() + "K";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
              .toPlainString() + "M";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
              .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
          + "TB";
    }
}
